/**
 * @file key_params.c
 * @brief 
 * @author  ()
 * @version 1.0
 * @date 2024-11-04
 * @ingroup flash
 * @copyright Copyright (C) 2019 Queclink Wireless Solutions (ShenZhen) Co., Ltd. All Rights Reserved.
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2024-11-04 <td>1.0     <td>     <td>内容
 * </table>
 */
#define LOG_TAG "PARM"
#include "easylog/elog.h"

#include "key_params.h"
#include "utils/utils_crc16.h"

#include "bsp/inc/bsp_iflash.h"
#define  KEY_OFFSET (0x8000)
#define  KEY_BASE (BANK_1_ADDR + KEY_OFFSET)

/*
 * @brief	   加载备份参数
 * @param[in]  offset - 首扇区偏移地址
 * @param[in]  crc_offset    - crc在缓冲区内偏移
 * @return 	   true - 加载成功
 **/
bool load_key_params(int32_t offset, unsigned char *buf, int32_t len, int32_t crc_offset)
{
    int rlen, crc, check = 0;
    rlen = bsp_iflash_read(KEY_BASE + offset, buf, len);
    if (rlen != len)
        return false;

    if(crc_offset >= 0) { 
        crc = (buf[crc_offset + 1] << 8) | buf[crc_offset];
        check = stdlib_get_crc16(buf, crc_offset);
        if (check != crc)
        {
            return false;
        }
        
        return check == crc;
    }
    else {
        return true;
    }
}

/*
 * @brief	   保存备份参数
 * @param[in]  offset - 首扇区偏移地址
 * @param[in]  crc_offset    - crc在缓冲区内偏移
 * @return 	   true - 加载成功
 **/
bool save_key_params(int32_t offset, unsigned char *buf, int32_t len, int32_t crc_offset)
{
    int ret, crc = 0;    
    if(crc_offset >= 0)
    {
        crc = stdlib_get_crc16(buf, crc_offset);
        buf[crc_offset + 1] = crc >> 8;
        buf[crc_offset] = crc & 0xff;
    }
    ret = bsp_iflash_write_random(KEY_BASE + offset, buf, len);
    if (ret != 0)
    {
        FLASH_DBG(LOG_FATAL "Save key params failed! id:%d,%d\r\n", offset, ret);
    }
    return ret == 0;
}


